import { defineStore } from 'pinia'
import type { IDialog, IHandleApi, IStatsChart } from 'vue3-common/types'
import { ElMessage } from 'element-plus'
import { IAnniversary } from '@/types/anniversary.ts'
import {
  addAnniversaryApi,
  deleteAnniversaryApi,
  queryAnniversaryApi, queryAnniversaryCategoryApi,
  updateAnniversaryApi
} from '@/apis/anniversary'
import { isBeforeDate } from 'vue3-common/utils/dateUtil'
import { getHolidays } from '@/utils/home/anniversaryUtil'

export const useAnniversaryStore = defineStore('anniversary', {
  state: () => ({
    anniversaryList: [] as IAnniversary[],
    queryInfo: {
      category: ''
    },
    anniversaryApiType: 'ADD' as IHandleApi,
    categoryStats: {} as IStatsChart[],
    currentAnniversary: {
      id: 0,
      title: '',
      date: '',
      recurring: false,
      type: 'countUp',
      category: ''
    } as IAnniversary,
    anniversaryDialog: {
      visible: false,
      title: '',
      data: {}
    } as IDialog<IAnniversary>,
    isRefresh: false
  }),
  actions: {
    async queryAnniversaryList() {
      this.anniversaryList = await queryAnniversaryApi(this.queryInfo.category || '')

      if (!this.queryInfo.category) {
        await this.queryHolidaysList()
      }
    },
    async queryHolidaysList() {
      const holidays = await getHolidays()
      holidays.forEach((item: any, index: number) => {
        if (isBeforeDate(new Date(), item.date)) {
          const dateItem: IAnniversary = {
            id: index,
            category: '节假日',
            date: item.date,
            recurring: false,
            title: item.localName,
            type: 'countDown'
          }
          this.anniversaryList.push(dateItem)
        }
      })
    },
    async queryAnniversaryCategory() {
      this.categoryStats = await queryAnniversaryCategoryApi()
    },
    async handleAnniversaryApi(anniversary: IAnniversary) {
      switch (this.anniversaryApiType) {
        case 'ADD':
          await addAnniversaryApi(anniversary)
          ElMessage.success('新增纪念日成功')
          break
        case 'UPDATE':
          await updateAnniversaryApi(anniversary.id as number, anniversary)
          ElMessage.success('更新纪念日成功')
          break
        case 'DELETE':
          await deleteAnniversaryApi(anniversary.id as number)
          ElMessage.success('删除纪念日成功')
          break
        default:
          break
      }
      this.anniversaryDialog.visible = false
      await this.refreshInfo()
    },
    async refreshInfo() {
      await this.queryAnniversaryList()
      this.isRefresh = !this.isRefresh
    },
    getEmptyAnniversary(): IAnniversary {
      return {
        category: '',
        date: '',
        recurring: false,
        title: '',
        type: 'countDown'
      }
    }
  }
})
